package pdi.IO;


import java.io.File;
import java.io.FilenameFilter;
import java.nio.file.Paths;
import java.util.List;


import pdi.OpenCvCaller;
import pdi.core.Image;
import utils.MyUtils;

public class RawImgWriter extends ImgWriter {

	protected String dirPath;
	protected boolean cleanDirectory;

	public RawImgWriter(String dirPath) {
		super();
		this.dirPath = dirPath;
		this.cleanDirectory = false;
	}
	public RawImgWriter(String dirPath, boolean clean) {
		super();
		this.dirPath = dirPath;
		this.cleanDirectory = clean;
	}


	@Override
	public void open() {
		//check if exist
		File dir = new File(dirPath);
		if(!dir.exists() || !dir.isDirectory())
			throw new IllegalArgumentException("There isn't a derectory on the requested path");

		//clean the directory
		if(this.cleanDirectory){
			File[] files = getAllImageFiles(dirPath);
			for (File file : files) {
				file.delete();				
			}
		}			
	}

	@Override
	public void close() {}

	@Override
	public void writeNext(Image img) {
		if(img.getMatrixRepresentation() == null)
			throw new IllegalArgumentException("Image with null matrix repressenatation can't be saved as image format");

		String finalPath = Paths.get(this.dirPath, img.getName()).toString();
		OpenCvCaller.getInstance().writeImage(finalPath, img.getMatrixRepresentation());		
	}

	@Override
	public void writeAll(List<Image> imgs) {
		
		open();
		
		if(imgs != null && imgs.size() > 0){
			for (Image img : imgs) {
				writeNext(img);
			}		
		}
		
		close();
	}

}
